/*
 * @Author: 鱿鱼溪学院
 * @Date: 2025-11-08 11:00:00
 * @LastEditTime: 2025-11-08 20:38:52
 * @LastEditors: 鱿鱼溪学院
 * @Description: Sequelize数据库配置
 * @FilePath: \jmd-ser-ts\app\db\sequelize.ts
 * Copyright 鱿鱼溪学院 by edu v1.0
 * 天道酬勤
 */
import { Sequelize } from "sequelize-typescript";
import dbConfig from "../../config/config.db";
import models from "../model/index";

/**
 * Sequelize数据库实例
 */
let sequelize: Sequelize | null = null;

/**
 * 初始化Sequelize连接
 */
export const initSequelize = async (): Promise<void> => {
  try {
    // 创建Sequelize实例
    sequelize = new Sequelize({
      host: dbConfig.db_host || "localhost",
      username: dbConfig.db_user || "root",
      password: dbConfig.db_pwd || "",
      database: dbConfig.db_name || "example_db",
      port: dbConfig.db_port ? Number(dbConfig.db_port) : 3306,
      dialect: "mysql",
      dialectModule: require("mysql2"),
      define: {
        // 自动添加 createdAt 和 updatedAt 字段
        timestamps: true,
        // 表名不使用复数
        freezeTableName: true,
        // 使用下划线命名（例如：created_at 而不是 createdAt）
        underscored: true,
      },
      pool: {
        max: dbConfig.pool?.max || 10,
        min: dbConfig.pool?.min || 0,
        acquire: dbConfig.pool?.acquire || 30000,
        idle: dbConfig.pool?.idle || 10000,
      },
      logging: dbConfig.logging ? console.log : false,
      models: Object.values(models), // 注册所有模型
    });

    try {
      // 测试连接
      await sequelize.authenticate();
      console.log("Sequelize连接成功");

      // 自动同步模型（开发环境使用，生产环境建议使用迁移）
      if (process.env.NODE_ENV === "development") {
        // 同步模型到数据库，不强制删除现有表
        await sequelize.sync({ force: false });
        console.log("模型同步已完成");
      } else {
        console.log("模型同步配置已准备（非开发环境）");
      }
    } catch (connectionError) {
      // 连接失败时只记录警告，不阻止服务器启动
      console.warn(
        "Sequelize连接测试失败（可能需要启动MySQL服务）:",
        (connectionError as Error).message
      );
      console.warn("服务器将继续启动，但数据库功能可能不可用");
    }
  } catch (error) {
    console.error("Sequelize连接失败:", error);
    throw error;
  }
};

/**
 * 获取Sequelize实例
 */
export const getSequelize = (): Sequelize => {
  if (!sequelize) {
    throw new Error("Sequelize实例未初始化，请先调用initSequelize()");
  }
  return sequelize;
};

/**
 * 关闭Sequelize连接
 */
export const closeSequelize = async (): Promise<void> => {
  if (sequelize) {
    await sequelize.close();
    sequelize = null;
    console.log("Sequelize连接已关闭");
  }
};

/**
 * 注册模型目录（用于自动加载模型）
 * @param modelPaths 模型文件路径数组
 */
export const registerModels = (modelPaths: string[]): void => {
  const sequelizeInstance = getSequelize();
  modelPaths.forEach((path) => {
    sequelizeInstance.addModels([path]);
  });
};

// 默认导出
export default {
  initSequelize,
  getSequelize,
  closeSequelize,
  registerModels,
};
